﻿using System;
using System.IO;

using SharpCompress.Archives;
using SharpCompress.Archives.Zip;
using SharpCompress.Common;
using SharpCompress.Readers;

namespace Utils.Compress
{
    public class CompressHelper
    {
 
        public static void WriteToDirectory(string filePath, string destinationDirectory)
        {
            using Stream stream = File.OpenRead(filePath);
            WriteToDirectory(stream, destinationDirectory, filePath);
        }


        public static void WriteToDirectory(Stream stream, string destinationDirectory, string fileName)
        {
            string extension = Path.GetExtension(fileName);
            if (extension.EndsWith("zip"))
            {
                WriteZipToDirectory(stream, destinationDirectory);
            }
            else if (extension.EndsWith("rar"))
            {
                WriteRarToDirectory(stream, destinationDirectory);
            }
            else
            {
                throw new ArgumentException("不支持的压缩文件");
            }
        }

        public static void WriteRarToDirectory(Stream stream, string destinationDirectory)
        {
            using var reader = ReaderFactory.Open(stream);
            while (reader.MoveToNextEntry())
            {
                if (!reader.Entry.IsDirectory)
                {
                    reader.WriteEntryToDirectory(destinationDirectory, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
                }
            }
        }

        public static void WriteZipToDirectory(Stream stream, string destinationDirectory)
        {
            using var archive = ArchiveFactory.Open(stream);
            foreach (var entry in archive.Entries)
            {
                if (!entry.IsDirectory)
                {
                    entry.WriteToDirectory(destinationDirectory, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
                }
            }
        }

        public static Stream CreateRarToStream(string fileDirectory)
        {
            using var archive = ZipArchive.Create();
            MemoryStream memoryStream = new MemoryStream();
            archive.AddAllFromDirectory(fileDirectory);
            archive.SaveTo(memoryStream);
            memoryStream.Position = 0;
            return memoryStream;
        }

        public static void CreateRarToFile(string fileDirectory, string filePath)
        {
            using FileStream fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
            using var archive = ZipArchive.Create();
            archive.AddAllFromDirectory(fileDirectory);
            archive.SaveTo(fileStream);
            fileStream.Flush();
        }

    }
}
